/*******************************************************************************
 * Copyright (c) 2010 Torkild U. Resheim
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Torkild U. Resheim - initial API and implementation
 *******************************************************************************/
package no.resheim.buildmonitor.ui.views.commands;

import java.lang.reflect.InvocationTargetException;

import no.resheim.buildmonitor.core.data.Job;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.internal.junit.model.JUnitModel;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.statushandlers.StatusManager;

public class OpenJUnitView extends AbstractCommandHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		Object obj = getSelection(event);
		if (obj != null && obj instanceof Job) {
			importTestRunSession("http://norvm-tools-m.norway.atmel.com/hudson/job/itests-as4e-3.x_win32.win32.x86/ws/test/as4e-ide/com.atmel.avr.sf.uc3.test.UC3A3_ExampleProjects.xml");
			try {
				PlatformUI.getWorkbench().getActiveWorkbenchWindow()
						.getActivePage()
						.showView("org.eclipse.jdt.junit.ResultView");
			} catch (PartInitException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	static void importTestRunSession(final String url) {
		try {
			PlatformUI.getWorkbench().getProgressService()
					.busyCursorWhile(new IRunnableWithProgress() {
						@SuppressWarnings("restriction")
						public void run(IProgressMonitor monitor)
								throws InvocationTargetException,
								InterruptedException {
							JUnitModel.importTestRunSession(url, monitor);
						}
					});
		} catch (InterruptedException e) {
			// cancelled
		} catch (InvocationTargetException e) {
			CoreException ce = (CoreException) e.getCause();
			StatusManager.getManager().handle(ce.getStatus(),
					StatusManager.SHOW | StatusManager.LOG);
		}
	}
}
